package com.bw.a2209clubshop.ui.login

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.TypedValue
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.bw.a2209clubshop.IntentData
import com.bw.a2209clubshop.R
import com.bw.a2209clubshop.base.BaseFragment
import com.bw.a2209clubshop.base.state.Default
import com.bw.a2209clubshop.base.state.Empty
import com.bw.a2209clubshop.base.state.Failed
import com.bw.a2209clubshop.base.state.Loading
import com.bw.a2209clubshop.base.state.Success
import com.bw.a2209clubshop.databinding.FragmentSmsCodeBinding
import com.bw.a2209clubshop.observeWithLifecycle
import com.bw.a2209clubshop.ui.login.viewModel.LoginViewModel
import com.bw.a2209clubshop.utils.ToastUtils


class SmsCodeFragment : BaseFragment<LoginViewModel, FragmentSmsCodeBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_sms_code
    private val mViewModel: LoginViewModel by activityViewModels()
    private lateinit var secSpan: ForegroundColorSpan
    private lateinit var textSpan: ForegroundColorSpan
    private lateinit var mNavController: NavController
    private val mAction by lazy {
        arguments?.getString(IntentData.KEY_ACTION_SMS_CODE) ?: ""
    }
    private val mRestSmsCodeSuccess by lazy {
        arguments?.getBoolean(IntentData.KEY_REST_SMS_CODE_SUCCESS) ?: false
    }
    //当前验证码
    private var mCurrentSmsCode: String = ""

    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp > 60_000) {
                onCountDownFinished()
            } else {
                onTick(60 - (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp) / 1000)
            }
        }
    }
    override fun initView() {
        mNavController = Navigation.findNavController(mBinding.root)
        mViewModel.setShowingFragmentTag(SmsCodeFragment::class.simpleName!!)
        val typedValue = TypedValue()
        requireContext().theme.resolveAttribute(R.attr.colorTheme, typedValue, true)
        secSpan = ForegroundColorSpan(typedValue.data)
        requireContext().theme.resolveAttribute(R.attr.colorLightText, typedValue, true)
        textSpan = ForegroundColorSpan(typedValue.data)
    }
    override fun initListener() {
        super.initListener()
        mBinding.tvResend.setOnClickListener {
//            if (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp < 60_000) {
//                return@setOnClickListener
//            }
            mViewModel.requestRest = false
            mViewModel.getSmsCode(mAction)
        }
        mViewModel.requestSmsCodeEvent.observeWithLifecycle(this, Lifecycle.State.STARTED) {
            when (it) {
                is Success -> {
                    mBinding.verifyView.showSoftKeyBoard()
                    mViewModel.sendSmsCodeTimeStamp = System.currentTimeMillis()
                    setLoadingViewVisible(false)
                    if (mAction != SmsCode.RESET.type)
//                        ToastUtils.showShort(requireContext(), "验证码已发送")
                    showCountDown()

                }
                is Loading -> {
                    setLoadingViewVisible(true)
                }
                is Failed -> {
                    setLoadingViewVisible(false)
                    onCountDownFinished()
                    if (mAction != SmsCode.RESET.type)
                        ToastUtils.showShort(requireContext(), it.message)

                }
                Default -> {
                    if (mAction != SmsCode.RESET.type)
                        ToastUtils.showShort(requireContext(), "请输入手机号D")
                }
                Empty -> {
                    if (mAction != SmsCode.RESET.type)
                        ToastUtils.showShort(requireContext(), "请输入手机号E")
                }
            }
        }
        mViewModel.requestLoginEvent.observeWithLifecycle(this, Lifecycle.State.CREATED) {
            when (it) {
                is Success -> {
                    setLoadingViewVisible(false)
                    //验证码登录成功
//                    (activity as? LoginActivity)?.handleLoginSuccess()

                }
                is Loading -> {
                    setLoadingViewVisible(true)
                }
                is Failed -> {
                    setLoadingViewVisible(false)
                    mBinding.verifyView.showSoftKeyBoard()
                    ToastUtils.showShort(requireContext(), it.message)
                }

                Default -> {}
                Empty -> {}
            }
        }
        mBinding.verifyView.setOnInputVerifyCodeCompleted {
            if (mAction == SmsCode.LOGIN.type) {
//                验证码登录
                mViewModel.loginBySmsCode(it)
            } else if (mAction == SmsCode.RESET.type) {
                //校验验证码
//                mViewModel.checkSmsCode(it)
                mCurrentSmsCode = it
            } else if (mAction == SmsCode.BIND.type) {
//                mViewModel.wxAttach2Phone(it)
            }
        }


//        observeEvent<LoginActivity.ClickAreaEvent>(requireActivity()) {
//            if (isOutsideOfView(mBinding.verifyView, it.ev)) {
//                mBinding.verifyView.hidePaste()
//            }
//        }
    }
    private fun isOutsideOfView(v: View?, event: MotionEvent): Boolean {
        if (v != null) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }
    override fun initData() {
        mBinding.viewmodel = mViewModel
        if (mViewModel.requestRest) {
            //重置密码页面返回，不自动获取新的验证码
            onCountDownFinished()
        } else {
            //重置密码，不在此页面发送
            if (mAction != SmsCode.RESET.type) {
                mViewModel.getSmsCode(mAction)
            } else {
                mViewModel.resetSmsCodeEvent(mRestSmsCodeSuccess)
            }
        }
    }
    private fun onCountDownFinished() {
        mBinding.tvResend.visibility = View.VISIBLE
        mBinding.tvCountDown.visibility = View.GONE
    }
    private fun showCountDown() {
        mBinding.tvCountDown.visibility = View.VISIBLE
        mBinding.tvResend.visibility = View.GONE
        mCountDownHandler.sendEmptyMessage(1)
    }
    private fun onTick(sec: Long) {
        val content = "$sec 秒后重新获取"
        val builder = SpannableStringBuilder(content)
        builder.setSpan(secSpan, 0, content.indexOf("秒"), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        builder.setSpan(textSpan, content.indexOf("秒"), content.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        mBinding.tvCountDown.text = builder
        mCountDownHandler.sendEmptyMessageDelayed(1, 1_000)
    }
}
enum class SmsCode(val type: String) {
    LOGIN("login"), RESET("rest"), BIND("bind")
}